<template>
  <div class="addAndEditRole base-addAndEditRole">
    <el-table
      ref="tableRef"
      :data="tableData"
      border
      stripe
      row-key="id"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection"></el-table-column>
      <el-table-column prop="id" label="ID" />
      <el-table-column prop="roleName" label="权限名称" />
      <el-table-column prop="roleDesc" label="权限描述" />
    </el-table>

    <el-row justify="center" style="margin: 10px 0">
      <el-button type="primary" @click="handleSaveOrBack(true)">保存</el-button>
      <el-button @click="handleSaveOrBack(false)">返回</el-button>
    </el-row>
  </div>
</template>

<script setup>
import { ref, onMounted, useTemplateRef, nextTick } from "vue";
import Mitt from "@/mitt/index.js";
const emits = defineEmits(["sendData"]);

const tableData = ref([]);
const tableRef = useTemplateRef("tableRef");

//复选框勾选的记录集合
const multipleSelection = ref([]);

//表格左侧勾选
const handleSelectionChange = (rows) => {
  console.log(rows);
  multipleSelection.value = rows;
};

//左侧默认选中，传递的是每一个符合条件的对象
const toggleSelection = (row) => {
  tableRef.value.toggleRowSelection(row);
};

const handleSaveOrBack = (type) => {
  //如果是保存，调用保存的接口，否则直接返回
  if (type) {
    console.log(multipleSelection.value);
  }

  emits("sendData", {
    showComponents: "viewAll",
    type: "",
  });
};
//获取数据
const getList = () => {
  //通过接口筛选出来的数据需要依次调用  toggleSelection 这个函数用来默认勾选

  //需要展示的数据
  let data1 = [
    {
      id: 1,
      roleName: "超级管理员",
      roleDesc: "ROLE_ADMIN",
    },
    {
      id: 2,
      roleName: "系统用户",
      roleDesc: "ROLE_USER",
    },
    {
      id: 3,
      roleName: "经理",
      roleDesc: "ROLE_MANAGER",
    },
    {
      id: 4,
      roleName: "文员",
      roleDesc: "ROLE_CLERK",
    },
  ];

  //需要勾选的数据
  let data2 = [
    {
      id: 1,
      roleName: "超级管理员",
      roleDesc: "ROLE_ADMIN",
    },
  ];
  tableData.value = data1;
  //得到被勾选的数据id
  const checkIds = data2.map((row) => row.id);
  //必须使用nextTick等表格渲染完毕之后才能勾选
  nextTick(() => {
    tableData.value.forEach((item) => {
      if (checkIds.includes(item.id)) {
        toggleSelection(item);
      }
    });
  });
};

onMounted(() => {
  Mitt.emit("sendcrumbsInfo", { first: "权限管理", second: "添加权限表单" });
  getList();
});
</script>

<style lang="less" scoped></style>
